<template>
	<div id="calendar"></div>
</template>

<script lang="ts" setup name="calendar">
	import '@fullcalendar/core/vdom'
	import {
		Calendar,
		EventClickArg,
		EventContentArg
	} from '@fullcalendar/core'
	import daygridPlugin from '@fullcalendar/daygrid'
	import interactionPlugin, {
		DateClickArg
	} from '@fullcalendar/interaction'
	import {
		ref,
		onMounted,
		watch
	} from 'vue'

	let calendar = ref()

	let props = defineProps({
		local: {
			type: String,
			default: 'zh-cn'
		},

		initialView: {
			type: String,
			default: 'dayGridMonth'
		},

		buttonText: {
			type: Object,
			default: () => {
				return {
					today: '今天',
					month: '月',
					week: '周',
					day: '日',
					prevYear: '上一年',
					nextYear: '下一年',
					prev: '上一月',
					next: '下一月'
				}
			}
		},

		headerToolbar: {
			type: Object,
			default: () => {
				return {
					start: 'title',
					center: '',
					end: 'prev today next'
				}
			}
		},

		footerToolbar: {
			type: Object
		},

		events: {
			type: Array,
			default: () => []
		},

		eventContent: {
			type: Function
		}
	})

	let emits = defineEmits(['date-click', 'event-click'])

	let renderCalendar = () => {
		let el = document.getElementById('calendar')
		if (el) {
			calendar.value = new Calendar(el, {
				plugins: [daygridPlugin, interactionPlugin],
				initialView: props.initialView,
				locale: props.local,
				buttonText: props.buttonText,
				headerToolbar: props.headerToolbar,
				footerToolbar: props.footerToolbar,
				eventContent: props.eventContent,
				displayEventEnd: true,

				eventSources: [{
					events(e, callback) {
						if (props.events.length) callback(props.events)
						else callback([])
					}
				}],

				dateClick(info) {
					emits('date-click', info)
				},

				eventClick(info) {
					emits('event-click', info)
				},
			})

			calendar.value.render()
		}
	}

	watch(() => props.events, () => {
		renderCalendar()
	}, {
		deep: true
	})

	onMounted(() => {
		renderCalendar()
	})
</script>

<style scoped>

</style>
